<template>
	<div class="container-page">
		<div class="container-bdody">
			<div class="version-box flex_row mt20">
				<el-row>
					<el-col :span="12" class="flex_row">
						<div class="">版本信息：</div>
						<div class="bold">{{ objectForm.v_title || '--' }}</div>
					</el-col>
					<el-col :span="12" class="flex_row">
						<div class="">企业成员：</div>
						<div class="bold">{{ objectForm.num_cps || '--' }}</div>
					</el-col>
					<el-col :span="12" class="flex_row">
						<div class="">销售权限：</div>
						<div class="bold">{{ objectForm.max_order || '--' }}</div>
					</el-col>
					<el-col :span="12" class="flex_row">
						<div class="">到期时间：</div>
						<div class="bold">{{ objectForm.endtime || '--' }}</div>
					</el-col>
				</el-row>
			</div>
			<el-form ref="formRef" :model="objectForm" :rules="objectRules" label-width="140px">
				<el-form-item label="企业图标">
					<div class="active-box">
						<UploadPhotos :list="photoList" @update:list="updatePhotoList" :limit="1" />
					</div>
				</el-form-item>
				<el-form-item label="企业名称" prop="name">
					<el-input v-model="objectForm.name" class="input-w" placeholder="请填写企业名称" maxlength="50"
						show-word-limit></el-input>
				</el-form-item>
				<el-form-item label="所在行业" prop="btype">
					<el-select v-model="objectForm.btype" placeholder="请选择" class="input-w">
						<el-option v-for="item in getHangyeList" :key="item.id" :label="item.title" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="所在地区">
					<el-cascader id="selectPrCtAr" v-model="objectForm.districtCodeArr" :options="optionsPosition"
						:props="propsdata" placeholder="省市区" @change="handleChange" class="input-w"></el-cascader>
				</el-form-item>
				<el-form-item label="详细地址" prop="address">
					<el-input type="text" v-model="objectForm.address" class="input-w" placeholder="详细地址"
						show-word-limit></el-input>
				</el-form-item>
				<el-form-item label="介绍照片" prop="photoQyList">
					<div class="active-box">
						<UploadPhotos :list="photoQyList" @update:list="updateQyPhotoList" :limit="99" />
					</div>
				</el-form-item>
				<el-form-item label="介绍简洁" prop="desc">
					<el-input type="textarea" rows="10" v-model="objectForm.desc" class="" placeholder="介绍简洁"
						show-word-limit></el-input>
				</el-form-item>
			</el-form>
			<div style="height: 50px;"></div>
		</div>
		<div class="container-footer flex_between">
			<div class="summary-info">
				<div class="font_size14">发布：</div>
				<div>
					<el-checkbox size="mini" v-model="objectForm.onoff_yd" true-label="1" false-label="2" label="云店上架"
						border></el-checkbox>
					<el-checkbox size="mini" v-model="objectForm.onoff_as" true-label="1" false-label="2" label="爱搜上架"
						border></el-checkbox>
				</div>
			</div>
			<div class="action-buttons">
				<!-- <el-button @click="cancelFun" size="small" class="btn-cancel">取 消</el-button> -->
				<el-button type="primary" @click="submitHandle" size="large" class="btn-confirm"> 保 存 </el-button>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, defineProps, defineEmits, watch, computed } from '@vue/composition-api'
import config from "@/js/conf/Config.js"
import UploadPhotos from "@/components/commV2/UploadPhotos/index.vue"

// 定义组件 props
const props = defineProps({
	getYunShopList: {
		type: Array,
		default: () => []
	},
})
const getHangyeList = ref([]) // 行业列表
const optionsPosition = ref([]) //省市区列表
const propsdata = ref({
	children: "cityList",
	label: "name",
	value: "code",
	expandTrigger: "hover",
	checkStrictly: true,
}) //省市区列表

// 表单引用
const formRef = ref(null)
// 表单验证规则
const objectRules = ref({
	name: [
		{ required: true, message: '请输入企业名称', trigger: 'blur' }
	],
	btype: [
		{ required: true, message: '请选择行业', trigger: 'change' }
	],
})

const photoList = ref([])
const updatePhotoList = (newList) => {
	photoList.value = newList
}

const photoQyList = ref([])
const updateQyPhotoList = (newList) => {
	console.log('updatePhotoList', newList)
	photoQyList.value = newList
}

// 获取当前组件实例
const { proxy } = getCurrentInstance()

// 表单数据
const objectForm = ref({
	districtCodeArr: [], // 省市区代码数组
	district: '', // 地区名称字符串
})


// 提交保存
const submitHandle = async () => {
	// 表单验证
	const valid = await proxy.$refs.formRef.validate()
	if (!valid) {
		proxy.$message({
			message: '请完善表单信息',
			type: 'warning'
		})
		return
	}
	try {
		const districtArr = objectForm.value.districtCodeArr || []
		let params = {
			...objectForm.value,
			logo: photoList.value[0]?.name || "",
			imgs: photoQyList.value && photoQyList.value.length > 0 ? photoQyList.value.map(vn => {
				return vn?.name
			}).join(',') : '',
			province: districtArr[0] || "",
			city: districtArr[1] || "",
			area: districtArr[2] || "",
		}
		let res = await proxy.$api({ url: config.compset_company_save, data: params })
		if (res.status == 1) {
			proxy.$message.success('操作成功')
			getCmpanyInfo()
		} else {
			proxy.$message.error(res?.msg || '操作失败')
		}
	} catch (error) { }
}


// 获取详情
const getCmpanyInfo = async () => {
	try {
		let res = await proxy.$api({ url: config.compset_company_info, data: {} })
		let result = res.data
		if (res.status == 1 && result) {
			objectForm.value = {
				...result,
				districtCodeArr: [],
			}
			photoList.value = result.logo ? [{ url: result.logo,name: result.logo_rel}] : []
			let imgs_ls = []
			try {
				if (result.imgs_ls) {
					if (typeof result.imgs_ls === 'string') {
						imgs_ls = JSON.parse(result.imgs_ls)
					} else if (Array.isArray(result.imgs_ls)) {
						imgs_ls = result.imgs_ls
					}
				}
			} catch (parseError) {
				imgs_ls = []
			}
			photoQyList.value = imgs_ls && imgs_ls.length > 0 ? imgs_ls.map(vm => {
				return {
					url: vm.img,
					name: vm.img_rel,
				}
			}) : []

			// 正确设置省市区代码数组实现地址回填
			const districtCodes = []
			if (result.province) districtCodes.push(result.province)
			if (result.city) districtCodes.push(result.city)
			if (result.area) districtCodes.push(result.area)
			objectForm.value.districtCodeArr = districtCodes
			// 同时更新地区名称字符串
			if (districtCodes.length > 0 && optionsPosition.value?.length > 0) {
				objectForm.value.district = getmapNameFun(districtCodes)
			}
		}
	} catch (error) {
	}
}

// 获取行业
const getBtypeLs = async () => {
	try {
		let res = await proxy.$api({ url: config.compset_btype_ls, data: {} })
		let result = res.data
		if (res.status == 1 && result) {
			// 检查数据结构，可能是 result.ls 或者直接是 result
			getHangyeList.value = result.ls || result
		}
	} catch (error) {
		console.error('获取行业数据失败:', error)
	}
}

// 表单验证
const submitForm = (formName) => {
	formRef.value.validate(async (valid) => {
		if (valid) { } else {
			console.log('error submit!!')
			return proxy.$message.error("请检查表单内容")
		}
	})
}

// 获取省市区
const getdistrictsData = async () => {
	let res = await proxy.$api({ url: config.COMM_DISTRICTS, data: {} });
	if (!res) return;
	if (res.status == 1 && res.data) {
		optionsPosition.value = res.data;
		// 省市区数据加载完成后，再获取企业信息进行地址回填
		await getCmpanyInfo();
	}
}

const handleChange = (value) => {
	if (value && value.length > 0) {
		objectForm.value.district = getmapNameFun(value)
	} else {
		objectForm.value.district = ''
	}
}

// 获取地址名称
const getmapNameFun = (arr) => {
	let name = "";
	const province = arr[0] | "";
	const city = arr[1] | "";
	const area = arr[2] | "";
	if (province) {
		optionsPosition.value.map((v) => {
			if (province == v.code) {
				name += v.name;
				if (city) {
					v.cityList.map((vs) => {
						if (city == vs.code) {
							name += vs.name;
							if (area) {
								vs.cityList.map((vw) => {
									if (area == vw.code) {
										name += vw.name;
									}
								});
							}
						}
					});
				}
			}
		});
	}
	return name;
}

const restFun = () => {
	formRef.value?.resetFields()
	objectForm.value = {
		districtCodeArr: [],
		district: ''
	}
	photoList.value = []
	photoQyList.value = []
}

defineExpose({
	restFun,
	objectForm,
})

onMounted(async () => {
	// 先加载行业数据
	await getBtypeLs()
	// 再加载省市区数据，加载完成后会自动获取企业信息
	await getdistrictsData()
})


</script>

<style lang="scss" scoped>
.container-page {
	width: 100%;
	height: 100%;
	max-height: 100vh;
	/* 限制最大高度为视窗高度 */
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	overflow: hidden;
	/* 防止整体容器溢出 */

	.container-bdody {
		box-sizing: border-box;
		flex: 1;
		height: 0;
		/* 关键修复：设置高度为0，让flex-grow生效 */
		min-height: 0;
		/* 确保flex项可以收缩 */
		padding-right: 100px;
		overflow-y: auto;

		.version-box {
			padding: 20px;
			background-color: rgba(236, 248, 255, 1.0);
			border-radius: 6px;
			border-left: 3px solid #00A0E9;
			margin-bottom: 20px;
			font-size: 16px;
			margin-left: 60px;
		}
	}

	.container-footer {
		border-top: 1px solid #f1f1f1;
		margin-top: 10px;
		padding: 14px 10px 4px;

		.summary-info {
			display: flex;
			align-items: center;
			gap: 16px;
		}

		.action-buttons {
			display: flex;
			gap: 12px;

			.btn-cancel {
				border-color: #cbd5e1;
				color: #64748b;
			}

			.btn-confirm {
				background-color: #3b82f6;
				border-color: #3b82f6;
			}
		}
	}

}

::v-deep .el-checkbox{
	margin-right: 0 !important;
}
.input-w{
	width: 400px;
}
</style>